import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Input,
  Select,
  Cascader,
  Button,
  Dropdown,
  Menu,
  Divider,
  Table,
  message,
  Badge,
  Tooltip,
  Modal,
} from 'antd';
import { DownOutlined } from '@ant-design/icons';

import LongLinkSetting from './components/LongLinkSetting';
import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { pathname } = window.location;
const { Item } = Menu;

const statusTypes: any[] = ['default', 'error', 'success'];
const statusTexts = ['', '调试', '运营'];
const qrCodePath = '/thanos/cab/qrCode';

const commandArrays = [
  {
    pathName: 'cab_multiSendCmd',
    cmdStr: 'upgrade',
    type: 1,
    title: '升级软件',
  },
  {
    pathName: 'cab_multiSendCmd',
    cmdStr: 'upgrade_hard',
    type: 1,
    title: '升级固件',
  },
  {
    pathName: 'cab_multiSendCmd',
    cmdStr: 'upgrade_sys',
    type: 1,
    title: '升级系统',
  },
  {
    pathName: 'cab_cacheFlush',
    cmdStr: 'flush_cache',
    type: 2,
    title: '清空缓存',
  },
  {
    pathName: 'cab_sendCmd',
    cmdStr: 'upload_log',
    type: 3,
    title: '上传日志',
  },
  {
    pathName: 'cab_sendCmd',
    cmdStr: 'upload_order',
    type: 3,
    title: '上传订单',
  },
  {
    pathName: 'cab_sendCmd',
    cmdStr: 'download_order',
    type: 3,
    title: '下载订单',
  },
];

interface CabinetManageListProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: boolean;
  location: { query: any };
  dataInfo: any;
  cabHWareList: any;
  gardenList: any;
  INITINFO: any;
  screen: string;
  hasPath: boolean;
  isMobile: boolean;
}

interface CabinetManageListState {
  searchValues: any;
  disableVisible: boolean;
  disableId: string | number;
  commandVisible: boolean;
  commandIndex: number;
  commandCode: string;
  batchCodes: string[];
  reloadVisible: boolean;
  reloadCabId: number;
  rowId: number;
  pageIndex: number;
  pageSize: number;
}

@connect(
  ({
    cabinetManagementList: { dataInfo, gardenList, cabHWareList },
    common: { INITINFO },
    global: { screen, isMobile, hasPath },
    loading,
  }: any) => ({
    dataInfo,
    gardenList,
    cabHWareList,
    INITINFO,
    screen,
    hasPath,
    isMobile,
    loading: loading.effects['cabinetManagementList/fetch'],
  }),
)
class CabinetManageListElem
  extends React.Component<CabinetManageListProps, CabinetManageListState> {
  columns: any = [
    {
      title: '柜体编号',
      dataIndex: 'code',
      width: 80,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '柜体名称',
      dataIndex: 'name',
      width: 100,
      render: (text: string, record: any) => (
        <Tooltip title={text}>
          <div
            className="wordOmit nameLink"
            onClick={() => this.handleShowCabiner(record.id, record.name)}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '连通状态',
      dataIndex: 'linkStatus',
      width: 80,
      render: (text: string) => {
        let showVal = <span>val</span>;
        if (text.indexOf('优') >= 0) {
          showVal = <span style={{ color: '#28ce20' }}>{text}</span>;
        } else if (text.indexOf('差') >= 0) {
          showVal = <span style={{ color: 'rgb(214, 58, 58)' }}>{text}</span>;
        }
        return (
          <Tooltip title={text}>
            <div className="wordOmit">{showVal}</div>
          </Tooltip>
        );
      },
    },
    {
      title: '格口',
      width: 180,
      children: [
        {
          title: '闲置',
          width: 48,
          dataIndex: 'free',
          render: (text:any) => text || 0,
        },
        {
          title: '总数',
          width: 40,
          dataIndex: 'cellCount',
          render: (text:any) => text || 0,
        },
        {
          title: '故障',
          width: 40,
          dataIndex: 'faultCount',
          render: (text:any) => text || 0,
        },
        {
          title: '占用率',
          width: 55,
          dataIndex: 'cellUsedRate',
          render: (text:any) => text || '0%',
        },
        {
          title: '操作',
          dataIndex: 'id',
          width: 40,
          render: (val: number, record: any) => (
            <span
              className="operLink"
              onClick={() => this.handleCellStatus(record)}
            >
              更多
            </span>
          ),
        },
      ],
    },
    {
      title: '偏差时间',
      dataIndex: 'verifyTime',
      width: 60,
    },
    {
      title: '断网次数',
      dataIndex: 'brokenCount',
      width: 60,
      render: (text: string) => text || '--',
    },
    { title: '布局', width: 50, dataIndex: 'layout' },
    { title: '结构', width: 50, dataIndex: 'structVersion' },
    {
      title: '软件',
      width: 60,
      dataIndex: 'softVersion',
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 50,
      render: (val: number) => <Badge status={statusTypes[val]} text={statusTexts[val]} />,
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 120,
      fixed: 'right',
      render: (id: number, record: any) => (
        <div>
          <span
            className="operLink"
            onClick={() => this.handleEditCabinet(id, record.name)}
          >
            编辑
          </span>
          <Divider type="vertical" />
          <span
            className="operLink"
            onClick={() => this.handleShowCabiner(id, record.name)}
          >
            详情
          </span>
          <Divider type="vertical" />
          <Dropdown arrow overlay={() => this.menu(record)}>
            <span className="operLink">
              更多 <DownOutlined />
            </span>
          </Dropdown>
        </div>
      ),
    },
  ];

  state: CabinetManageListState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    disableVisible: false,
    disableId: '',
    commandVisible: false,
    commandIndex: 0,
    commandCode: '',
    batchCodes: [],
    reloadVisible: false,
    reloadCabId: 0,
    rowId: 0,
  };

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query }, screen } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;

    return {
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchAction('common/fetchLogisList');
    this.fetchAction('common/fetchAddressList');

    const { dataInfo, hasPath } = this.props;
    if (dataInfo?.list?.length && !hasPath) return;
    if (hasPath) {
      const { dispatch } = this.props;
      dispatch({ type: 'global/clearPath' });
    }

    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  componentWillUnmount() {
    this.fetchAction('clearGarden');
  }

  setFieldsValue = () => {
    // 设置表单
    const { searchValues } = this.state;
    const { form: { setFieldsValue } } = this.props;
    const params = this.turnValuesType(searchValues);
    setFieldsValue(params);
  };

  turnValuesType = (values: any) => {
    const {
      pareaCode, careaCode, dareaCode, ...query
    } = values;
    const codes = [pareaCode, careaCode, dareaCode];

    return {
      // 转换数据类型
      ...query,
      areaCodes: codes.filter((item: any) => item),
    };
  };

  fetchDataValues = () => {
    this.fetchAction('fetch', this.getQueryParams());

    const {
      pareaCode,
      careaCode,
      dareaCode,
    } = this.getQueryParams();
    if (pareaCode) {
      const params = {
        pareaCode,
        careaCode,
        dareaCode,
      };
      this.fetchAction('fetchGarden', params);
    }
  };

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    return params;
  };

  menu = (record: any) => {
    const {
      id,
      code,
      name,
      hwareVersion,
    } = record;

    return (
      <Menu>
        <Item className="operLink" onClick={() => this.handleDisable(true, id)}>
          禁用
        </Item>
        <Item className="operLink" onClick={() => this.handleShowOperModal(true, 4, code)}>
          上传日志
        </Item>
        <Item className="operLink" onClick={() => this.handleShowOperModal(true, 5, code)}>
          上传订单
        </Item>
        <Item className="operLink" onClick={() => this.handleShowOperModal(true, 6, code)}>
          下载订单
        </Item>
        <Item className="operLink" onClick={() => this.handleShowOperModal(true, 3, code)}>
          更新缓存
        </Item>
        <Item className="operLink" onClick={() => this.fetchAction('fetchLongConfig', { change: true, code })}>
          长链配置
        </Item>
        <Item className="operLink" onClick={() => this.handleCabinerTrajectory(code, name)}>
          柜体轨迹
        </Item>
        <Item className="operLink" onClick={() => this.handleDownloadCode(id)}>
          下载二维码
        </Item>
        <Item className="operLink" onClick={() => this.handleUpdateLogs(id)}>
          修改日志
        </Item>
        {hwareVersion !== '2.0' && hwareVersion !== '3.0' && (
          <Item className="operLink" onClick={() => this.handleReloadCabModal(true, id)}>
            柜体重启
          </Item>
        )}
      </Menu>
    );
  }

  /**
   * 更多格口状态
   */
  handleCellStatus = (record: any) => {
    const {
      id,
      code,
      name,
      isCollection,
    } = record;

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${name}格口`,
      url: `/basic/cabinetManagement/list/mouthDetails/list?id=${id}&cabCode=${code}&name=${name}&isCollection=${isCollection}`,
    });
  };

  /**
   * 新建柜体
   */
  handleAddCabinet = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '新建柜体',
      url: '/basic/cabinetManagement/list/add',
    });
  };

  /**
   * 编辑柜体
   */
  handleEditCabinet = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `编辑${name}`,
      url: `/basic/cabinetManagement/list/edit?id=${id}`,
    });
  };

  /**
   * 查看柜体
   */
  handleShowCabiner = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${name}`,
      url: `/basic/cabinetManagement/list/detail?id=${id}`,
    });
  };

  /**
   * 断网统计
   */
  handleStatistics = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '断网统计',
      url: '/basic/cabinetManagement/list/broken',
      isTopMenu: true,
    });
  };

  /**
   * 柜体轨迹
   */
  handleCabinerTrajectory = (code: string, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `轨迹${name}`,
      url: `/basic/cabinetManagement/list/trajectory?code=${code}`,
    });
  };

  /**
   * 下载二维码
   */
  handleDownloadCode = (id: string) => {
    window.location.href = `${qrCodePath}?cabId=${id}&type=1`;
  };

  /**
   * 修改日志
   */
  handleUpdateLogs = (id: number) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '柜体管理日志',
      url: `/basic/cabinetManagement/list/logs?cabinetId=${id}`,
    });
  };

  /** 柜体重启弹窗 */
  handleReloadCabModal = (reloadVisible: boolean, id: number = 0) => {
    this.setState({
      reloadVisible,
      reloadCabId: id,
    });
  };

  /** 确定重启 */
  handleReloadCabConfirm = () => {
    const { reloadCabId: id } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'cabinetManagementList/reloadCab',
      payload: {
        id,
        search: this.getQueryParams(),
      },
    });

    this.handleReloadCabModal(false);
  };

  handleDisable = (disableVisible: boolean, id?: number) => {
    this.setState({ disableVisible, disableId: id || '' });
  };

  handleConfirmDisable = () => {
    const { disableId: id, searchValues: search } = this.state;
    const params = { search, id };
    this.fetchAction('disable', params);
    this.handleDisable(false);
  };

  /** 选择省市区 */
  handleChangeArea = (area: any) => {
    const { form: { resetFields } } = this.props;
    resetFields(['gardenId']);

    this.fetchAction('clearGarden');
  };

  handleValidation = () => {
    const { form: { getFieldValue } } = this.props;
    const value = getFieldValue('areaCodes');

    if (!value || value.length < 1) {
      this.fetchAction('fetchGarden');
    } else {
      const params = {
        pareaCode: value[0],
        careaCode: value[1],
        dareaCode: value[2],
      };
      this.fetchAction('fetchGarden', params);
    }
  };

  handleShowOperModal = (commandVisible: boolean, commandIndex: number, commandCode: string = '') => {
    const { batchCodes } = this.state;
    if (commandVisible && commandIndex >= 0 && commandIndex <= 2 && batchCodes.length <= 0) {
      message.warning('请选择需要升级的柜体');
    } else {
      this.setState({ commandVisible, commandIndex, commandCode });
    }
  };

  handleSubmitOper = () => {
    const {
      searchValues: search,
      commandIndex,
      commandCode,
      batchCodes,
    } = this.state;

    const { type, cmdStr, pathName } = commandArrays[commandIndex];
    const params: any = { search, cmdStr, pathName };

    if (type === 1) {
      params.codes = batchCodes.map((item: any) => item.code);
    } else {
      params.code = commandCode;
    }

    this.setState({ batchCodes: [] }, () => {
      this.fetchAction('operactionSet', params);
      this.handleShowOperModal(false, 0);
    });
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const { areaCodes = [], ...params } = values;
      const { screen } = this.props;
      const query: any = {
        ...params,
        pageIndex: 1,
        pageSize: screen === 'sm' ? 100 : 20,
      };
      if (areaCodes[0]) [query.pareaCode] = [areaCodes[0]];
      if (areaCodes[1]) [query.careaCode] = [areaCodes[1]];
      if (areaCodes[2]) [query.dareaCode] = [areaCodes[2]];

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '柜体管理',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    this.fetchAction('clearGarden');

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '柜体管理',
      url: pathname,
      isTopMenu: true,
    });
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };

    this.setState({ batchCodes: [] }, () => {
      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '柜体管理',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  fetchAction = (typeName: string, payload: any = {}) => {
    const type = typeName.indexOf('common') >= 0
      ? typeName : `cabinetManagementList/${typeName}`;

    const { dispatch } = this.props;
    dispatch({ type, payload });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  render() {
    const {
      pageIndex,
      pageSize,
      disableVisible,
      commandVisible,
      commandIndex,
      batchCodes,
      reloadVisible,
    } = this.state;

    const {
      form: { getFieldDecorator },
      INITINFO: { logisList, addressList },
      dataInfo,
      gardenList,
      screen,
      loading,
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = {
      total: dataInfo ? dataInfo.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${dataInfo.count || 0}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };

    const rowSelection: any = {
      // 勾选表单
      selectedRowKeys: batchCodes.map((item: any) => item.id),
      onChange: (selectedRowKeys: any, selectedRows: any) => {
        this.setState({ batchCodes: selectedRows });
      },
    };

    if (screen === 'sm') {
      rowSelection.columnWidth = 30;
    }

    if (screen === 'sm') {
      delete this.columns[this.columns.length - 1].fixed;
    } else if (screen === 'md' || screen === 'lg') {
      this.columns[this.columns.length - 1].fixed = 'right';
    }

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Form.Item label="柜体名称" colon={false}>
                  {getFieldDecorator('name')(<Input allowClear placeholder="请输入" />)}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="硬件版本" colon={false}>
                  {getFieldDecorator('hwareVersion')(
                    <Select allowClear placeholder="请选择">
                      <Option value="1.0">1.0</Option>
                      <Option value="2.0">2.0</Option>
                      <Option value="2.7">2.7</Option>
                      <Option value="3.0">3.0</Option>
                      <Option value="4.0">4.0</Option>
                      <Option value="5.0">5.0</Option>
                      <Option value="6.0">6.0</Option>
                      <Option value="7.0">7.0</Option>
                    </Select>,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="物流中心" colon={false}>
                  {getFieldDecorator('logisId')(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {logisList.map((item: any) => (
                        <Option value={String(item.id)} key={item.id}>{item.name}</Option>
                      ))
                      }
                    </Select>,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="柜体编号" colon={false}>
                  {getFieldDecorator('code')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Form.Item label="　省市区" colon={false}>
                  {getFieldDecorator('areaCodes', { initialValue: 0 })(
                    <Cascader
                      changeOnSelect
                      options={addressList}
                      placeholder="请选择"
                      onChange={this.handleChangeArea}
                    />,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="小区学校" colon={false}>
                  {getFieldDecorator('gardenId')(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      onFocus={this.handleValidation}
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {gardenList.map((item: any) => (
                        <Option value={String(item.id)} key={item.id}>{item.name}</Option>
                      ))
                      }
                    </Select>,
                  )}
                </Form.Item>
              </Col>
              <Col md={12} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={this.handleAddCabinet}
            >
              新建柜体
            </Button>
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={() => this.handleShowOperModal(true, 0)}
            >
              软件升级
            </Button>
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={() => this.handleShowOperModal(true, 1)}
            >
              固件升级
            </Button>
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={() => this.handleShowOperModal(true, 2)}
            >
              系统升级
            </Button>
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={this.handleStatistics}
            >
              断网统计
            </Button>
          </div>

          <Table
            rowKey="id"
            className="statementTable tableHeight60"
            tableLayout="fixed"
            rowSelection={rowSelection}
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 1600 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>
        <LongLinkSetting />

        <Modal
          title="提示信息"
          visible={disableVisible}
          okText="禁用"
          onOk={this.handleConfirmDisable}
          onCancel={() => this.handleDisable(false)}
        >
          <p>确定禁用当前柜体吗？</p>
        </Modal>
        <Modal
          title="确认提示"
          visible={commandVisible}
          destroyOnClose
          onOk={this.handleSubmitOper}
          onCancel={() => this.handleShowOperModal(false, 0)}
        >
          <p>亲，慎用哦！您确定要{commandArrays[commandIndex].title}?</p>
        </Modal>
        <Modal
          title="确认提示"
          visible={reloadVisible}
          destroyOnClose
          onOk={this.handleReloadCabConfirm}
          onCancel={() => this.handleReloadCabModal(false)}
        >
          <p>亲，慎用哦！您确定要重启当前柜体吗?</p>
        </Modal>
      </>
    );
  }
}

export default Form.create<CabinetManageListProps>()(CabinetManageListElem);
